package threads;

class SharedAccount {
	private double balance;

	public SharedAccount(double initialAmount) {
		balance = initialAmount;
		System.out.println("Current Balance: " + balance);
	}

	//public void completeTransaction(double amount) {
	public synchronized void completeTransaction(double amount) {
		double temp = this.balance + amount;

		if (amount < 0)
			System.out.println("Retirando: " + Math.abs(amount));
		else
			System.out.println("Depositando: " + amount);

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			System.out.println("Transaction interrupted.");
		}

		balance = temp;
		System.out.println("Current Balance: " + balance);
	}
}

class SharedAccountClient implements Runnable {
	double transaction;
	SharedAccount sa;

	public SharedAccountClient(SharedAccount sa) {
		this.sa = sa;
	}

	public void setTransaction(double transaction) {
		this.transaction = transaction;
	}

	public void run() {
		sa.completeTransaction(transaction);
	}
}

public class ThreadsBankAccountDemo {
	public static void main(String[] args) {
		SharedAccount sa = new SharedAccount(400.00);
		SharedAccountClient c1 = new SharedAccountClient(sa);
		SharedAccountClient c2 = new SharedAccountClient(sa);
		double x1 = 1000.00;
		double x2 = -400;

		c1.setTransaction(x1);
		c2.setTransaction(x2);

		Thread t1 = new Thread(c1);
		Thread t2 = new Thread(c2);
		t1.start();
		t2.start();
	}
}